package tgc.edu.ljc.custom;

import org.apache.commons.lang3.BooleanUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

public class CommonController<T extends BaseEnitity,ID,Form extends CommonForm> {
	@Autowired
	private CommonService<T, ID> baseService;
	private Class<T> clazz=GenericsUtils.getSuperClassGenricType(getClass());
	
	@RequestMapping(value="/manage")
	public void manage() {
		
	}
	
	@RequestMapping(value="/list")
	@ResponseBody
	public Object list(JqGridParam param) {
		Pageable pageable = param.buildPageable();
		Page<T> page;
		if(BooleanUtils.isTrue(param.getSearch())) {
			Specification spec = param.buildSpec();
			page=baseService.findAll(spec, pageable);
		}else {
			page=baseService.findAll(pageable);
		}
		return JqGridUtils.getResult(page);
	}
	
	@RequestMapping(value="/edit")
	@ResponseBody
	public Object edit(Form form,ID id) throws InstantiationException, IllegalAccessException {
		if("del".equals(form.getOper())) {
			baseService.deleteById(id);
		}else {
			T model=clazz.newInstance();
			BeanUtils.copyProperties(form, model,"id");
			if("edit".equals(form.getOper())) {
				model.setId(id);
			}
			baseService.save(model);
		}
		return "OK";
	}
}
